package edu.whut.controller;


import edu.whut.entity.Approval;
import edu.whut.entity.CommonResult;
import edu.whut.entity.Creation;
import edu.whut.entity.User;
import edu.whut.service.ApprovalService;
import edu.whut.service.CreationService;
import edu.whut.service.UserService;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RequestMapping("/approval")
@RestController
public class ApprovalController {

    @Resource
    ApprovalService approvalService;

    @Resource
    UserService userService;

    @Resource
    CreationService creationService;

    @RequestMapping("/like")
    public CommonResult<Approval> giveLike(@RequestBody Approval approval){
        Creation creation = creationService.getCreation(approval.getCreationId());
        User user = userService.getUserByName(creation.getUsername());
        if(user==null){
            return new CommonResult<>(400,"error",null);
        }
        user.setApproval(user.getApproval()+1);
        if(approvalService.addApproval(approval)&&userService.updateUser(user)){
            return new CommonResult<>(200,"success",null);
        }
        return new CommonResult<>(400,"error",null);
    }

    @RequestMapping("/withdraw")
    public CommonResult<Approval> withdrawLike(@RequestBody Approval approval){
        if(approvalService.deleteApproval(approval)){
            return new CommonResult<>(200,"success",null);
        }
        return new CommonResult<>(400,"error",null);
    }

    /**
     * 功能：得到点赞数
     * @param creationId
     * @return 点赞数
     */
    @RequestMapping("/getLikeNum")
    public CommonResult<Integer> getLikeNumber(@RequestParam("creationId") Long creationId){
        if(approvalService.getApprovalNumber(creationId)!=null){
            return new CommonResult<>(200,"success",approvalService.getApprovalNumber(creationId));
        }
        return new CommonResult<>(400,"error",null);
    }
}
